//
//  LocationManager.m
//  dmc
//
//  Created by teeking_scx on 2018/3/9.
//  Copyright © 2018年 桑赐相. All rights reserved.
//

#import "LocationManager.h"


@interface LocationManager()<CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager * locationManager;

@end
static LocationManager *_instance;
@implementation LocationManager

+ (instancetype)manager{
    if (_instance == nil) {
        _instance = [[LocationManager alloc] init];
    }
    return _instance;
}
+ (id)allocWithZone:(struct _NSZone *)zone{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}
-(void)startLocation{
    if([CLLocationManager locationServicesEnabled]){
        // 启动位置更新
        // 开启位置更新需要与服务器进行轮询所以会比较耗电，在不需要时用stopUpdatingLocation方法关闭;
        self.locationManager = [[CLLocationManager alloc] init];
        //设置定位的精度
        _locationManager.distanceFilter = 10.0f;
        _locationManager.delegate = self;
        [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
        [_locationManager requestWhenInUseAuthorization];
        //开始实时定位
        [_locationManager startUpdatingLocation];
    }
}
#pragma mark - CLLocationManagerDelegate
//代理,定位代理经纬度回调
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    CLLocation * newLoaction = locations[0];
    [self.locationManager stopUpdatingLocation];
    self.coordinate2D = newLoaction.coordinate;
    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
    [geoCoder reverseGeocodeLocation:newLoaction completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        for (CLPlacemark * place in placemarks) {
            
            NSLog(@"country == %@",place.country);
            NSString *country = place.country;
            NSString *locality = place.locality;
            NSString *subLocality = place.subLocality;
            if (subLocality != nil) {
                self.location = subLocality;
                self.locationBlock(subLocality);
            }else if (locality != nil){
                self.location = locality;
                self.locationBlock(locality);
            }else if(country != nil){
                self.location = country;
                self.locationBlock(country);
            }else{
                self.location = nil;
                self.locationBlock(@"定位失败");
            }
            if (![country isEqualToString:@"中国"]) {
                self.location = @"北京";
            }
        }
    }];
}

@end

